﻿@section Styles{
    <style>
        .demo-upload-list img {
            width: 100%;
            height: 100%
        }

        .demo-upload-list-cover {
            display: none;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, .6)
        }

        .demo-upload-list:hover .demo-upload-list-cover {
            display: block
        }

        .demo-upload-list-cover i {
            color: #fff;
            font-size: 20px;
            cursor: pointer;
            margin: 0 2px
        }

        .demo-upload-list {
            width: 100%;
            height: 130px;
            text-align: center;
            line-height: 130px;
            border: 1px solid transparent;
            border-radius: 4px;
            overflow: hidden;
            background: #fff;
            position: relative;
            box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
            margin-right: 4px;
        }

            .demo-upload-list img {
                width: 100%;
                height: 100%
            }

        .demo-upload-list-cover {
            display: none;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, .6)
        }

        .demo-upload-list:hover .demo-upload-list-cover {
            display: block
        }

        .demo-upload-list-cover i {
            color: #fff;
            font-size: 20px;
            cursor: pointer;
            margin: 0 2px
        }

        .blog-cover {
            margin-bottom: 0;
        }

        .ivu-date-picker {
            width: 100%;
        }

        .ivu-tag {
            margin: 0 4px 0;
        }
    </style>
}
<i-form :model="blog" ref="blog" :rules="ruleValidate" :label-width="60" id="blogForm" action="Post" method="post">
    <row>
        <i-col span="18">
            <Form-Item label="标题" prop="title">
                <i-input v-model="blog.title" placeholder="请输入标题..."></i-input>
            </Form-Item>
            <row>
                <i-col span="14">
                    <Form-Item label="标签" prop="tags">
                        <div class="ivu-input-wrapper ivu-input-wrapper-default ivu-input-type">
                            <input v-if="isEditTag" @@blur="isEditTag=0" autocomplete="off" spellcheck="false" type="text" placeholder="请输入标签..." class="ivu-input ivu-input-default" v-model="tagEditor">
                            <div class="ivu-input ivu-input-default" @@click="isEditTag=1" v-if="!isEditTag">
                                <Tag v-for="tag in tags" :key="tag" :name="tag" closable @@on-close="delTag">{{ tag }}</Tag>
                            </div>
                        </div>
                    </Form-Item>
                </i-col>
                <i-col span="2">&nbsp;</i-col>
                <i-col span="8">
                    <Form-Item label="日期" prop="created">
                        <Date-Picker v-model="blog.created" type="date" placeholder="请选择发布日期"></Date-Picker>
                    </Form-Item>
                </i-col>
            </row>
            <Form-Item label="概述" prop="overview">
                <i-input name="overview" v-model="blog.overview" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入概述..."></i-input>
            </Form-Item>
        </i-col>
        <i-col span="6">
            <Form-Item class="blog-cover">
                <div class="demo-upload-list" v-for="item in uploadList">
                    <template v-if="item.status === 'finished'">
                        <img :src="item.url">
                        <div class="demo-upload-list-cover">
                            <Icon type="ios-eye-outline" @@click.native="handleView(item.name)"></Icon>
                            <Icon type="ios-trash-outline" @@click.native="handleRemove(item)"></Icon>
                        </div>
                    </template>
                    <template v-else>
                        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </template>
                </div>
                <Upload ref="upload" :show-upload-list="false" :default-file-list="defaultList" :on-success="handleSuccess" :format="['jpg','jpeg','png']"
                        :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload"
                        multiple type="drag" action="/Admin/Blog/Upload" style="display: inline-block;width:100%;">
                    <div>
                        <Icon type="ios-camera" size="20"></Icon>
                    </div>
                </Upload>
                <Modal title="封面图片" v-model="visible">
                    <img :src="blog.cover" v-if="visible" style="width: 100%">
                </Modal>
            </Form-Item>
        </i-col>
    </row>
    <form-item label="内容">
        <div id="editor"></div>
    </form-item>
    <form-item>
        <i-button type="primary" @@click="handleSubmit()">保存</i-button>
        <i-button style="margin-left: 8px">取消</i-button>
    </form-item>
</i-form>

@section Scripts
    {
    <script type="text/javascript" src="/admin/editor/wangEditor.min.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                tags: ['随笔'],
                isEditTag: false,
                blog: {
                    title: '', cover: '', overview: '', views: 0, created: '',
                    blogContent: { blogId: 0, contnet: '', markDown: '' },
                    tags: [{ blogId: 0, name: '' }]
                },
                editor: null,
                defaultCover: {},
                defaultList: [
                    {
                        'name': 'no-image.png',
                        'url': '/images/no-image.png'
                    }
                ],
                visible: false,
                uploadList: [],
                ruleValidate: {
                    title: [
                        { required: true, message: '标题不能为空', trigger: 'blur' },
                        { type: 'string', max: 100, message: '最多不能超过100个字符', trigger: 'blur' }
                    ],
                    created: [
                        { required: true, type: 'date', message: '请选择发布日期', trigger: 'change' }
                    ],
                    tags: [
                        { required: true, type: 'array', min: 1, message: '请输入标签', trigger: 'change' }
                    ],
                    overview: [
                        { required: true, message: '请输入描述信息', trigger: 'blur' },
                        { type: 'string', min: 20, message: '描述信息不能少于20个字符', trigger: 'blur' }
                    ]
                }
            },
            computed: {
                tagEditor: {
                    get: function () {
                        return this.tags.join(',');
                    },
                    set: function (tag) {
                        this.tags = tag.split(',');
                    }
                }
            },
            mounted: function () {
                this.get();
                var E = window.wangEditor;
                this.editor = new E('#editor');
                this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024;
                this.editor.customConfig.uploadImgMaxLength = 3;
                this.editor.customConfig.customUploadImg = function (files, insert) {
                    var uploadData = new FormData();
                    for (var i = 0, j = files.length; i < j; i++) {
                        uploadData.append(files[i].name, files[i]);
                    }
                    var config = {
                        headers: { 'Content-Type': 'multipart/form-data' }
                    };
                    axios.post('/Admin/Blog/Upload', uploadData, config)
                        .then(response => {
                            for (var i = 0; j= response.data.length,i<j; i++) {
                                insert(response.data[i].url);
                            }
                        });
                };
                this.editor.create();
                
                this.uploadList = this.$refs.upload.fileList;
                this.defaultCover = this.uploadList[0];
            },
            methods: {
                get() {
                    let id = getQueryString('id');
                    if (id !== '0') {
                        axios.get('/Admin/Blog/GetBlog', { params: { id: id} })
                        .then(response => {
                            if (response.data) {
                                this.blog = response.data;
                                if (this.blog.tags && this.blog.tags.length>0) {
                                    this.tags.splice(0, 1);
                                    for (var i = 0, j = this.blog.tags.length; i < j; i++) {
                                        this.tags.push(this.blog.tags[i].name);
                                    }
                                }
                                if (this.blog.cover) {
                                    this.uploadList[0].url=this.blog.cover;
                                }
                                this.editor.txt.html(response.data.blogContent ? response.data.blogContent.content:'');
                            }
                        }).catch(function (err) {
                            app.$Message.error(err);
                        });
                    }
                },
                delTag(event, name) {
                    const index = this.tags.indexOf(name);
                    this.tags.splice(index, 1);
                },
                handleView(name) {
                    this.imgName = name;
                    this.visible = true;
                },
                handleRemove(file) {
                    if (file && file.url !== '/images/no-image.png') {
                        const fileList = this.$refs.upload.fileList;
                        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
                    }
                    if (this.uploadList.length === 0) {
                        this.uploadList.push(this.defaultCover);
                    }
                },
                handleSuccess(res, file) {
                    if (Array.isArray(file.response)) {
                        file.url = file.response[0].url;
                        file.name = file.response[0].name;
                    } else {
                        console.error(file.response);
                    }
                },
                handleFormatError(file) {
                    this.$Notice.warning({
                        title: '文件格式不正确',
                        desc: '文件 ' + file.name + ' 格式不正确,请选择 jpg 或 png格式的文件'
                    });
                },
                handleMaxSize(file) {
                    this.$Notice.warning({
                        title: '超过文件大小限制',
                        desc: '文件  ' + file.name + ' 太大, 上传文件不能超 2M'
                    });
                },
                handleBeforeUpload() {
                    this.$refs.upload.fileList.splice(0, 1);
                    return true;
                },
                handleSubmit() {
                    this.blog.cover = this.uploadList[0].url;
                    this.blog.blogContent.content = this.editor.txt.html();
                    this.blog.tags = [];
                    for (var i = 0, j = this.tags.length; i < j; i++) {
                        this.blog.tags.push({ BlogId:0, Name: this.tags[i] });
                    }
                    this.$refs['blog'].validate((valid) => {
                        let url = this.blog.id > 0 ? '/Admin/Blog/Update' : '/Admin/Blog/Post';
                        if (valid) {
                            axios.post(url, this.blog)
                                .then(function (response) {
                                    if (!response.data.succeeded) {
                                        app.$Message.error(response.data.errors[0].description);
                                    } else {
                                        app.$Message.success('操作成功');
                                        if (app.blog.id > 0) { location.href = '/Admin/Blog/Index'; }
                                    }
                                })
                                .catch(function (err) {
                                    app.$Message.error('操作失败');
                                    console.error(err);
                                });
                        } else {
                            this.$Message.error('数据验证失败');
                        }
                    });
                }
            }
        });
    </script>
}